package com.jxit0573.android.lib.net;

import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSONObject;
import com.jxit0573.android.lib.BuildConfig;
import com.jxit0573.android.lib.util.BackgroundTasks;
import com.jxit0573.android.lib.util.JsonUtils;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * @author jia
 */
public abstract class BaseRequestCallback<T> implements Callback {

    @Override
    public void onResponse(@NonNull final Call call, final Response response) {
        if (response.isSuccessful()) {
            try {
                String res = response.body().string();
                if (BuildConfig.DEBUG) {
                    JSONObject obj = new JSONObject();
                    obj.put("Request", call.request().toString());
                    obj.put("Response", res);
                    Log.e("接口调用", obj.toJSONString());
                }
                if (TextUtils.isEmpty(res)) {
                    BackgroundTasks.getInstance().post(() -> {
                        onFailure(response.code(), new IOException("response is null"));
                        response.close();
                        call.cancel();
                    });
                } else {
                    JSONObject.parseObject(res);
                    final T result = JsonUtils.parse(res, getType());
                    BackgroundTasks.getInstance().post(() -> {
                        onSuccess(result);
                        response.close();
                        call.cancel();
                    });
                }
            } catch (final IOException e) {
                BackgroundTasks.getInstance().post(() -> {
                    e.printStackTrace();
                    onFailure(response.code(), e);
                    response.close();
                    call.cancel();
                });
            }
        } else {
            BackgroundTasks.getInstance().post(() -> {
                int code = response.code();
                onFailure(code, new IOException("Http Code：" + code));
                response.close();
                call.cancel();
            });
        }
    }

    @Override
    public void onFailure(@NonNull final Call call, @NonNull final IOException exception) {
        BackgroundTasks.getInstance().post(() -> {
            onFailure(-1, exception);
            call.cancel();
        });
    }

    private Type getType() {
        return ((ParameterizedType) Objects.requireNonNull(getClass().getGenericSuperclass())).getActualTypeArguments()[0];
    }

    /**
     * 成功
     *
     * @param result 请求结果
     */
    public abstract void onSuccess(T result);

    /**
     * 失败
     *
     * @param code      异常编码
     * @param exception 异常信息
     */
    public abstract void onFailure(int code, IOException exception);

}